
#include <iostream>
#include "fstream"
#include <glog/logging.h>
#include <fmt/format.h>
#include "rt_spp.h"
using namespace std;
ostream &operator<<(ostream &os, Position &pos) {
  os << fmt::format("{:17.13} {:17.13} {:.4f} {:.4f} {:.4f} {:.4f} {:d} {:d}",
					pos.lat,
					pos.lon,
					pos.height,
					pos.std[0],
					pos.std[1],
					pos.std[2],
					pos.q,
					pos.ns);
  return os;
}

int main() {
  cout << "this file is for SPP test" << endl;
  google::LogToStderr();

  string nav_file_name = "/media/rebeater/hd_data2/workspace/raw_data/car/20201215/M39/201212154131.20N";
  string obs_file_name = "/media/rebeater/hd_data2/workspace/raw_data/car/20201215/M39/201212154131.20O";
  string bds_file_name = "/media/rebeater/hd_data2/workspace/raw_data/car/20201215/M39/201212154131.20F";
  string out_file = "/media/rebeater/hd_data2/workspace/raw_data/car/20201215/M39/201212154131_01.pos";
  ifstream nav_if(nav_file_name);
  ifstream obs_if(obs_file_name);
  ofstream ofs(out_file);
  string line;
  int gps_week;
  double gps_sec;
  gtime_t time;

  RealTimeSpp spp;
  /*load nav file*/
  spp.LoadNavFromRnx(nav_file_name);
  spp.LoadNavFromRnx(bds_file_name);
  /*load obs header to get current gps week and second*/
  int end_idx;
  do {
	getline(obs_if, line);
	end_idx = (int)line.find("END OF HEADER");
  } while (end_idx < 0);

  /*SPP!*/
  Position pos{};
  while (!obs_if.eof()) {
	getline(obs_if, line);
	if (line[0] == '>') { /*读取时间戳,计算秒脉冲*/
	  /*上一秒数据处理完毕了，计算位置并输出*/
	  if (spp.GetSppPosition(&pos)) {
		ofs << gps_week << " " << fmt::format("{:.3f}", gps_sec) << " " << pos << '\n';
		LOG(INFO) << gps_week << " " << fmt::format("{:.3f}", gps_sec) << " " << pos << '\n';
	  }
	  /*读取时间并且转换为GPS时间，用于下一步更新*/
	  if (str2time(line.c_str(), 2, 28, &time)) {
		LOG(ERROR) << "time get failed";
		return -1;
	  } else {
		gps_sec = time2gpst(time, &gps_week);
	  }
	} else { /* 读取数据 ，没有时间戳的那一行直接读取数据，不更新 */
	  spp.Update(gps_week, gps_sec, line.c_str());
	}
  }
  return 0;
}
